package com.intelligent.ispc.core.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ApplicationUtil;
import com.intelligent.ispc.common.utils.FileUtils;
import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.core.dto.*;
import com.intelligent.ispc.core.service.ExportFileService;
import com.intelligent.ispc.core.service.SpcAnalysisService;
import com.intelligent.ispc.core.service.SpcExportService;
import com.intelligent.ispc.export.spc.ExportCellFactory;
import com.intelligent.ispc.external.rcall.dto.ControlDataDto;
import com.intelligent.ispc.external.rcall.dto.ExportBaseObject;
import com.intelligent.ispc.external.rcall.dto.NormalDistributionDto;
import com.intelligent.ispc.external.rcall.dto.RuleResultDto;
import com.intelligent.ispc.external.rcall.service.AnalysisService;
import com.intelligent.ispc.foundation.poi.SampleExcelBuilder;
import com.intelligent.ispc.utils.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.core.task.TaskExecutor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by julia on 16/4/11.
 */
@Service
public class SpcExportServiceImpl implements SpcExportService {
    private static Logger logger = LoggerFactory.getLogger(SpcExportServiceImpl.class);

    @Autowired
    private SpcAnalysisService spcAnalysisService;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private ExportFileService exportFileService;


    @Autowired
    private SimpMessagingTemplate msgTemplate;

    @Autowired
    private SystemConfig systemConfig;

    @Override
    public void exportMultiItemsChartsToExcel(Map<String, Object> searchParams) {
        Subject subject = SecurityUtils.getSubject();
        SecurityUserDto dto = (SecurityUserDto) subject.getPrincipal();
        String loginName = dto.getLoginName();
        Long userId = dto.getId();
        searchParams.put("userId", userId);
        taskExecutor.execute(new Thread() {
            public void run() {
                String testItemNamesParam = (String) searchParams.get("itemNames");
                String[] testItemNames = testItemNamesParam.split(",");
                Arrays.sort(testItemNames);
                String projectName = (String) searchParams.get("projectName");
                String fileType = (String) searchParams.get("fileType");
                String projectId = (String) searchParams.get("projectId");

                DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd_HHmmss");
                DateTime now = new DateTime();
                String fix = now.toString(format);

                StringBuilder sb = new StringBuilder();
                sb.append("export_").append(projectName).append("_")
                        .append(loginName).append("_").append(fix)
                        .append(".").append(fileType);
                String fileName = sb.toString();
                String savePath = ApplicationUtil.getProjectPathWithSeparator() + "exports" + ApplicationUtil.getFileSeparator();

                String filePath = savePath + fileName;

                ExportFileDto exportFileDto = new ExportFileDto();
                exportFileDto.setCreateBy(loginName);
                exportFileDto.setCreateTime(now.toDate());
                exportFileDto.setProjectName(projectName);
                exportFileDto.setStatus(ExportFileStatus.EXPORTING.toString());
                exportFileDto.setUrl("exportsfile/" + fileName);
                exportFileDto.setDataType(DataSourceType.SPC.getCode());
                Long fileId = exportFileService.createExportFile(exportFileDto);

                logger.debug("Export NDCs to file:{}", fileName);

                try {
                    List<SimpleKeyValueDto> charts = Lists.newArrayList();
                    Map<String, Object> ndcMultiChartItemsMap = Maps.newHashMap();
                    List<ExportBaseObject> exportList = Lists.newArrayList();
                    List<ControlChartWarningRuleDto> ruleList = spcAnalysisService.searchCCWarningRuleByProject(projectId);
                    for (int i = 0; i < testItemNames.length; i++) {
                        searchParams.remove("itemNames");
                        searchParams.remove("fileType");
                        searchParams.put("itemName", testItemNames[i]);

                        StringBuilder sb1 = new StringBuilder();
                        sb1.append("export_").append(projectName).append("_")
                                .append(loginName).append("_").append(testItemNames[i]).append("_").append(fix)
                                .append(".").append("png");
                        String imgPath = ApplicationUtil.getProjectPathWithSeparator() + "exports/temp/";
                        File file = new File(imgPath);
                        if (!file.exists() && !file.isDirectory()) {
                            file.mkdir();
                        }
                        imgPath += sb1.toString();
//                        imgPath = imgPath.replaceAll(" ", "_");
                        List<TestItemDto> results = spcAnalysisService.searchTestItem(searchParams);
                        ndcMultiChartItemsMap.put(testItemNames[i], results);
                        if (results.size() < 2) {
                            continue;
                        }

                        int length = 0;
                        for (TestItemDto dto : results) {
                                if (dto.getIsNumeric() && !isBlank(dto.getTestedValue())) {
                                length++;
                            }
                        }
                        double[] data = new double[length];
                        int n = 0;
                        for (TestItemDto dto : results) {
                            if (dto.getIsNumeric() && !isBlank(dto.getTestedValue())) {
                                data[n] = Double.parseDouble(dto.getTestedValue());
                                n++;
                            }
                        }
                        Double usl = null;
                        Double lsl = null;
                        if (results.get(results.size() - 1).getUpperLimit() != null) {
                            usl = Double.parseDouble(results.get(results.size() - 1).getUpperLimit());
                        }
                        if (results.get(results.size() - 1).getLowerLimit() != null) {
                            lsl = Double.parseDouble(results.get(results.size() - 1).getLowerLimit());
                        }
//                        searchParams.put("filePath", imgPath);
                        SimpleKeyValueDto chartDto = new SimpleKeyValueDto();
                        chartDto.setKey(testItemNames[i]);
                        chartDto.setValue(imgPath);
                        charts.add(chartDto);

                        Map<String, Object>searchMap = Maps.newHashMap();
                        searchMap.put(Constant.ANALYSE_TYPE, Constant.ANALYSE_MRC_TYPE);
                        ControlDataDto controlDataMRDto = analysisService.analyseControlChart(searchMap, results, ruleList);
                        searchMap.put(Constant.ANALYSE_TYPE, Constant.ANALYSE_RUNC_TYPE);
                        ControlDataDto controlDataRUNDto = analysisService.analyseControlChart(searchMap, results, ruleList);
                        double xbar = (controlDataRUNDto.getMeanData())[3];
                        String[] xxbarValue = new String[results.size()];
                        for (int k=0; k< results.size(); k++) {
                                if (results.get(k) != null && results.get(k).getIsNumeric() && !isBlank(results.get(k).getTestedValue())) {
                                double value = (Double.valueOf(results.get(k).getTestedValue()) - xbar);
                                xxbarValue[k] = String.format("%." + 6 + "f", value);
                            }
                            else {
                                xxbarValue[k] = "-";
                            }
                        }

                        ExportBaseObject exportObj = new ExportBaseObject();
                        exportObj.setAnalyseData(data);
                        exportObj.setFilePath(imgPath);
                        exportObj.setItemName(testItemNames[i]);
                        exportObj.setUsl(usl);
                        exportObj.setLsl(lsl);
                        exportObj.setMrValue(controlDataMRDto.getData());
                        exportObj.setXxbarValue(xxbarValue);
                        exportList.add(exportObj);
                    }
                    searchParams.put("charts", exportList);
                    searchParams.put("exportCharts", charts);
                    List<CPWarningRuleDto> cpWarningRules = spcAnalysisService.searchCPWarningRuleByProject(projectId);
                    Map<String, Object> dataResult = analysisService.exportMultipleNDC2Img(searchParams, cpWarningRules);
                    ExportCellFactory exportCellFactory = new ExportCellFactory();
                    exportCellFactory.buildSPCMultiItems(searchParams, dataResult, ndcMultiChartItemsMap);

                    SampleExcelBuilder sampleExcelBuilder = new SampleExcelBuilder();
                    sampleExcelBuilder.drawExcel(filePath, exportCellFactory);

                    String[] chartStr = new String[charts.size()];
                    for (int i = 0; i < charts.size(); i++) {
                        chartStr[i] = charts.get(i).getValue().toString();
                    }
                    FileUtils.deleteFile(chartStr);
                    //delete pictures
                    exportFileService.updateExportFileStatus(fileId, ExportFileStatus.FINISHED);
                } catch (Exception e) {
                    logger.error("export multi ndc failed!", e);
                    exportFileService.updateExportFileStatus(fileId, ExportFileStatus.FAILED);
                }

                msgTemplate.setUserDestinationPrefix("/data/");
                msgTemplate.convertAndSend("/topic/data/exportDownloadListener#" + userId, "{'result':'success','url':'"+ exportFileDto.getUrl() +"'}");
            }
        });
    }

    @Override
    public void exportSingleItemChartsToExcel(Map<String, Object> searchParams) {
        Subject subject = SecurityUtils.getSubject();
        SecurityUserDto dto = (SecurityUserDto) subject.getPrincipal();
        String loginName = dto.getLoginName();
        Long userId = dto.getId();
        searchParams.put("userId", userId);
        taskExecutor.execute(new Thread() {
            public void run() {
                String projectName = (String) searchParams.get("projectName");
                String chartType = (String) searchParams.get("chartTypes");
                String itemName = (String) searchParams.get("itemName");

                String charts[] = chartType.split(",");
                Map<String, Object> imageMap = new HashMap<String, Object>();
                DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd_HHmmss");
                DateTime now = new DateTime();
                String fix = now.toString(format);
                String[] imgPathStr = new String[charts.length];
                for (int i = 0; i < charts.length; i++) {
                    StringBuilder sb1 = new StringBuilder();
                    sb1.append("export_").append(projectName).append("_")
                            .append(loginName).append("_").append(charts[i]).append("_").append(fix)
                            .append(".").append("png");
                    String imgPath = ApplicationUtil.getProjectPathWithSeparator() + "exports/temp/";
                    File file = new File(imgPath);
                    if (!file.exists() && !file.isDirectory()) {
                        file.mkdir();
                    }
                    imgPath += sb1.toString();
                    imageMap.put(charts[i], imgPath);
                    imgPathStr[i] = imgPath;
                }

                StringBuilder sb = new StringBuilder();
                sb.append("export_").append(projectName).append("_")
                        .append(itemName).append("_").append(fix)
                        .append(".").append("xls");

                String fileName = sb.toString();
                String savePath = ApplicationUtil.getProjectPathWithSeparator() + "exports" + ApplicationUtil.getFileSeparator();
                File file = new File(savePath);
                if (!file.exists() && !file.isDirectory()) {
                    file.mkdir();
                }
//                searchParams.put("filePath", savePath + sb1.toString());
//                searchParams.put("savePath", savePath + sb.toString());
                String filePath = savePath + sb.toString();

                ExportFileDto exportFileDto = new ExportFileDto();
                exportFileDto.setCreateBy(loginName);
                exportFileDto.setCreateTime(now.toDate());
                exportFileDto.setProjectName(projectName);
                exportFileDto.setStatus(ExportFileStatus.EXPORTING.toString());
                exportFileDto.setUrl("exportsfile/" + fileName);
                exportFileDto.setDataType(DataSourceType.SPC.getCode());

                Long fileId = exportFileService.createExportFile(exportFileDto);

                logger.debug("Export excle to file:{}", fileName);

                try {
                    List<TestItemDto> testItemDtos = spcAnalysisService.searchTestItem(searchParams);
                    List<CPWarningRuleDto> cpWarningRuleDtos = Lists.newArrayList();
                    List<ControlChartWarningRuleDto> ruleList = Lists.newArrayList();

                    if (searchParams.containsKey("projectId")) {
                        String projectId = (String) searchParams.get("projectId");
                        cpWarningRuleDtos = spcAnalysisService.searchCPWarningRuleByProject(projectId);
                        ruleList = spcAnalysisService.searchCCWarningRuleByProject(projectId);
                    }
                    searchParams.put("exportCharts", imageMap);
                    Map<String, Object> result = analysisService.exportAllCharts2ImgForItem(searchParams, testItemDtos, cpWarningRuleDtos, ruleList);
                    Map<String, Object>searchMap = Maps.newHashMap();
                    searchMap.put(Constant.ANALYSE_TYPE, Constant.ANALYSE_MRC_TYPE);
                    ControlDataDto controlDataMRDto = analysisService.analyseControlChart(searchMap, testItemDtos, ruleList);
                    searchMap.put(Constant.ANALYSE_TYPE, Constant.ANALYSE_RUNC_TYPE);
                    ControlDataDto controlDataRUNDto = analysisService.analyseControlChart(searchMap, testItemDtos, ruleList);
                    double xbar = (controlDataRUNDto.getMeanData())[3];
                    String[] xxbarValue = new String[testItemDtos.size()];
                    for (int i=0; i< testItemDtos.size(); i++) {
                            if (testItemDtos.get(i) != null && testItemDtos.get(i).getIsNumeric() && !isBlank(testItemDtos.get(i).getTestedValue())) {
                            double value = (Double.valueOf(testItemDtos.get(i).getTestedValue()) - xbar);
                            xxbarValue[i] = String.format("%." + 6 + "f", value);
                        }
                        else {
                            xxbarValue[i] = "-";
                        }
                    }

                    editRuleDescription(ruleList);
                    result.put("testItemDtos", testItemDtos);
                    result.put("ruleList", ruleList);
                    result.put("mrValue", controlDataMRDto.getData());
                    result.put("xxbarValue", xxbarValue);

                    ExportCellFactory exportCellFactory = new ExportCellFactory();
                    exportCellFactory.buildSPC4SingleItem(searchParams, result);


                    SampleExcelBuilder sampleExcelBuilder = new SampleExcelBuilder();
                    sampleExcelBuilder.drawExcel(filePath, exportCellFactory);

                    FileUtils.deleteFile(imgPathStr);     //delete pictures

                    exportFileService.updateExportFileStatus(fileId, ExportFileStatus.FINISHED);
                } catch (Exception e) {
                    logger.error("export failed!", e);
                    exportFileService.updateExportFileStatus(fileId, ExportFileStatus.FAILED);
                }

                msgTemplate.setUserDestinationPrefix("/data/");
                msgTemplate.convertAndSend("/topic/data/exportDownloadListener#" + userId, "{'result':'success','url':'"+ exportFileDto.getUrl() +"'}");
            }
        });
    }

    private void editRuleDescription(List<ControlChartWarningRuleDto> ruleList) {
        for (int i = 0; i < ruleList.size(); i++) {
            String title = "";
            ControlChartWarningRuleDto ccrd = ruleList.get(i);
            switch (ruleList.get(i).getCode()) {
                case "R1":
                    title = ccrd.getDetailRule().replaceAll("\\[n\\]", ccrd.getPoints() + "").replaceAll("\\[s\\]", ccrd.getSigma() + "");
                    break;
                case "R2":
                case "R3":
                    title = ccrd.getDetailRule().replaceAll("\\[n\\]", ccrd.getPoints() + "");
                    break;
                case "R4":
                case "R7":
                case "R8":
                    title = ccrd.getDetailRule().replaceAll("\\[n\\]", ccrd.getPoints() + "").replaceAll("\\[s\\]", ccrd.getSigma() + "");
                    break;

                case "R5":
                case "R6":
                    title = ccrd.getDetailRule().replaceAll("\\[n\\]", ccrd.getPoints() + "").replace("\\[s\\]", ccrd.getSigma() + "").replaceAll("\\[m\\]", ccrd.getSomePoints() + "");
                    break;
                default:
                    break;
            }
            ccrd.setDetailRule(title);
        }
    }

    private void exportNDChart2Excel(Map<String, Object> searchParams) {
        try {
            List<TestItemDto> testItemDtos = spcAnalysisService.searchTestItem(searchParams);
            List<CPWarningRuleDto> cpWarningRuleDtos = Lists.newArrayList();
            if (searchParams.containsKey("projectId")) {
                String projectId = (String) searchParams.get("projectId");
                cpWarningRuleDtos = spcAnalysisService.searchCPWarningRuleByProject(projectId);
            }
            NormalDistributionDto results = analysisService.exportNDChart2Img(searchParams, testItemDtos, cpWarningRuleDtos);
            OutputStream out = new FileOutputStream(searchParams.get("savePath").toString());

            searchParams.put("usl", StringUtils.isBlank(testItemDtos.get(testItemDtos.size() - 1).getUpperLimit()) ? "-" : testItemDtos.get(testItemDtos.size() - 1).getUpperLimit());
            searchParams.put("lsl", StringUtils.isBlank(testItemDtos.get(testItemDtos.size() - 1).getLowerLimit()) ? "-" : testItemDtos.get(testItemDtos.size() - 1).getLowerLimit());

            List<List<String>> data0 = new ArrayList<List<String>>();
            List rowData0 = new ArrayList();
            //condition
            rowData0.add(setSearchParams(searchParams, "projectName"));
            rowData0.add(setSearchParams(searchParams, "stationId"));
            rowData0.add(setSearchParams(searchParams, "slotNo"));
            rowData0.add(setSearchParams(searchParams, "serialNumber"));
            rowData0.add(setSearchParams(searchParams, "startTime"));
            rowData0.add(setSearchParams(searchParams, "stopTime"));
            rowData0.add(Integer.toString(testItemDtos.size()));

            //Statistical
            rowData0.add("");
            rowData0.add("");
            rowData0.add("");
            rowData0.add(setNdsValue(results, "count", searchParams));
            rowData0.add(setNdsValue(results, "avg", searchParams));
            rowData0.add(setNdsValue(results, "max", searchParams));
            rowData0.add(setNdsValue(results, "min", searchParams));
            rowData0.add(setNdsValue(results, "range", searchParams));
            rowData0.add(setNdsValue(results, "std", searchParams));
            rowData0.add(setNdsValue(results, "lcl", searchParams));
            rowData0.add(setNdsValue(results, "ucl", searchParams));

            //Constant
            rowData0.add("");
            rowData0.add("");
            rowData0.add("");

            rowData0.add(setNdsValue(results, "group", searchParams));
            rowData0.add(setNdsValue(results, "usl", searchParams));
            rowData0.add(setNdsValue(results, "lsl", searchParams));
            rowData0.add(setNdsValue(results, "center", searchParams));

            //Capability Index
            rowData0.add("");
            rowData0.add("");
            rowData0.add("");
            rowData0.add(setNdsValue(results, "ca", searchParams));
            rowData0.add(setNdsValue(results, "cpk", searchParams));
            rowData0.add(setNdsValue(results, "cp", searchParams));
            rowData0.add(setNdsValue(results, "cpl", searchParams));
            rowData0.add(setNdsValue(results, "cpu", searchParams));
            data0.add(rowData0);

            List<List<String>> data = new ArrayList<List<String>>();
            for (TestItemDto dto : testItemDtos) {
                List rowData = new ArrayList();
                rowData.add(dto.getSerialNumber());
                rowData.add(dto.getUpperLimit());
                rowData.add(dto.getLowerLimit());
                rowData.add(dto.getUnitName());
                rowData.add(dto.getTestedValue());
                rowData.add(dto.getIsPass() == true ? "PASS" : "FAIL");
                data.add(rowData);
            }
            String[] headers0 = {"PROJECT", "STATION", "SLOT", "SN", "START TIME", "STOP TIME", "Total Items", "", "",
                    "Statistical", "Samples", "AVG", "Max", "Min", "Range", "StDev", "LCL", "UCL", "", "", "Constant", "Groups",
                    "USL", "LSL", "Center", "", "", "Capability Index", "CA", "CPK", "CP", "CPL", "CPU"};

            String[] headers = {"Serial Number", "Upper Limit", "Lower Limit", "Unit Name", "Tested Value", "Is Pass"};
            ExportExcelUtils eeu = new ExportExcelUtils();
            HSSFWorkbook workbook = new HSSFWorkbook();

            eeu.exportNDCExcel(workbook, 0, "Chart", headers0, data0, searchParams, out);
            eeu.exportNDCExcel(workbook, 1, searchParams.get("itemName").toString(), headers, data, searchParams, out);
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            throw new ApplicationException(e.getMessage());
        }

    }

    private void exportRChart2Excel(Map<String, Object> searchParams) {
        try {
            String type = null;
            if (searchParams.get(Constant.ANALYSE_TYPE) != null) {
                type = searchParams.get(Constant.ANALYSE_TYPE).toString();
                searchParams.remove(Constant.ANALYSE_TYPE);
            }

            List<TestItemDto> testItemDtos = spcAnalysisService.searchTestItem(searchParams);
            int totalNumber = testItemDtos.size();

            searchParams.put(Constant.ANALYSE_TYPE, type);
            List<ControlChartWarningRuleDto> ruleList = Lists.newArrayList();
            if (searchParams.containsKey("projectId")) {
                String projectId = (String) searchParams.get("projectId");
                ruleList = spcAnalysisService.searchCCWarningRuleByProject(projectId);
            }

            ControlDataDto controlDataDto = analysisService.exportRChart2Img(searchParams, testItemDtos, ruleList);

            OutputStream out = new FileOutputStream(searchParams.get("savePath").toString());

            List<List<String>> data0 = new ArrayList<List<String>>();
            List rowData0 = new ArrayList();
            rowData0.add(setSearchParams(searchParams, "projectName"));
            rowData0.add(setSearchParams(searchParams, "stationId"));
            rowData0.add(setSearchParams(searchParams, "slotNo"));
            rowData0.add(setSearchParams(searchParams, "serialNumber"));
            rowData0.add(setSearchParams(searchParams, "startTime"));
            rowData0.add(setSearchParams(searchParams, "stopTime"));
            rowData0.add(Integer.toString(testItemDtos.size()));
            rowData0.add("");
            rowData0.add("");
            data0.add(rowData0);
            List<RuleResultDto> ruleResultDtos = controlDataDto.getRuleResultList();
            for (int i = 0; i < ruleResultDtos.size(); i++) {
                List rowData = new ArrayList();
                rowData.add(ruleResultDtos.get(i).getRuleName());
                rowData.add(ruleResultDtos.get(i).isOverRule() == true ? "true" : "false");
                rowData.add(Long.toString(ruleResultDtos.get(i).getPos()));
                String details = ruleList.get(i).getDetailRule();
                String r = details.replace("[n]", ruleList.get(i).getPoints().toString());
                r = r.replace("[m]", ruleList.get(i).getSomePoints().toString());
                r = r.replace("[s]", ruleList.get(i).getSigma().toString());
                rowData.add(r);
                data0.add(rowData);
            }

            List<List<String>> data = new ArrayList<List<String>>();
            for (TestItemDto dto : testItemDtos) {
                List rowData = new ArrayList();
                rowData.add(dto.getSerialNumber());
                rowData.add(dto.getUpperLimit());
                rowData.add(dto.getLowerLimit());
                rowData.add(dto.getUnitName());
                rowData.add(dto.getTestedValue());
                rowData.add(dto.getIsPass() == true ? "PASS" : "FAIL");
                data.add(rowData);
            }
            String[] headers0 = {"PROJECT", "STATION", "SLOT", "SN", "START TIME", "STOP TIME", "Total Items",
                    "", "", "Judge Rules"};
            String[] headers = {"Serial Number", "Upper Limit", "Lower Limit", "Unit Name", "Tested Value", "Is Pass"};
            ExportExcelUtils eeu = new ExportExcelUtils();
            HSSFWorkbook workbook = new HSSFWorkbook();
            eeu.exportRExcel(workbook, 0, "Chart", headers0, data0, searchParams, out);
            eeu.exportRExcel(workbook, 1, testItemDtos.get(0).getName(), headers, data, searchParams, out);
            //原理就是将所有的数据一起写入，然后再关闭输入流。
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            throw new ApplicationException(e.getMessage());
        }

    }

    private String setSearchParams(Map<String, Object> searchParams, String key) {
        if (searchParams != null && key != null && searchParams.containsKey(key)) {
            return searchParams.get(key).toString();
        } else
            return "-";
    }

    private String setNdsValue(NormalDistributionDto results, String key, Map<String, Object> searchParams) {
        String result = "";
        if (results != null && key != null && results.getNdsDataItem() != null) {
            switch (key) {
                case "count":
                    return Double.toString(results.getNdsDataItem().getDataCount()).split("\\.")[0];
                case "avg":
                    return String.format("%.6f", results.getNdsDataItem().getAvgValue());
                case "max":
                    return String.format("%.6f", results.getNdsDataItem().getMaxValue());
                case "min":
                    return String.format("%.6f", results.getNdsDataItem().getMinValue());
                case "range":
                    return String.format("%.6f", results.getNdsDataItem().getRangeValue());
                case "std":
                    return String.format("%.6f", results.getNdsDataItem().getStdValue());
                case "lcl":
                    return String.format("%.6f", results.getNdsDataItem().getLclValue());
                case "ucl":
                    return String.format("%.6f", results.getNdsDataItem().getUclValue());
                default:
            }

        }
        if (results != null && key != null && results.getStaDataItem() != null) {
            switch (key) {
                case "group":
                    return Integer.toString(results.getStaDataItem().getGroupValue());
                case "usl":
                    return searchParams.get("usl").toString();
                case "lsl":
                    return searchParams.get("lsl").toString();
                case "center":
                    if (results.getStaDataItem().getCenterValue() == null) {
                        return "-";
                    }
                    return String.format("%.6f", results.getStaDataItem().getCenterValue());
                default:
            }

        }
        if (results != null && key != null && results.getPcDataItem() != null) {
            switch (key) {
                case "ca":
                    if (results.getPcDataItem().getCaData() == null) {
                        return "-";
                    }
                    return String.format("%.4f", results.getPcDataItem().getCaData().getValue()) + "%" + "," + results.getPcDataItem().getCaData().getgType();
                case "cpk":
                    if (results.getPcDataItem().getCpkData() == null) {
                        return "-";
                    }
                    return String.format("%.6f", results.getPcDataItem().getCpkData().getValue()) + "," + results.getPcDataItem().getCpkData().getgType();
                case "cp":
                    if (results.getPcDataItem().getCpData() == null) {
                        return "-";
                    }
                    return String.format("%.6f", results.getPcDataItem().getCpData().getValue()) + "," + results.getPcDataItem().getCpData().getgType();
                case "cpl":
                    if (results.getPcDataItem().getCplData() == null) {
                        return "-";
                    }
                    return String.format("%.6f", results.getPcDataItem().getCplData().getValue()) + "," + results.getPcDataItem().getCplData().getgType();
                case "cpu":
                    if (results.getPcDataItem().getCpuData() == null) {
                        return "-";
                    }
                    return String.format("%.6f", results.getPcDataItem().getCpuData().getValue()) + "," + results.getPcDataItem().getCpuData().getgType();
                default:
            }

        }
        return "-";
    }

    private boolean isBlank(String d) {
        if (StringUtils.isBlank(d)) {
            return true;
        }

        if (d.equalsIgnoreCase("N/A") || d.equalsIgnoreCase("-")
                || d.equalsIgnoreCase("nil") || d.equalsIgnoreCase("UnKown Line") ||
                d.equalsIgnoreCase("_")) {
            return true;
        }

        return false;
    }
}
